package com.uaijug.dengue.servlet;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.uaijug.dengue.core.Foco;
import com.uaijug.dengue.dao.PMF;

/**
 * Servlet que retorna uma Lista de Focos para o celular
 * 
 * Utiliza a DataOutputStream para serializar cada Foco
 * 
 * @author ricardo
 * 
 */
public class ListaFocosServlet extends HttpServlet {

	private static final long serialVersionUID = -6306758361807580596L;
	PersistenceManager pm = PMF.get().getPersistenceManager();
	BlobstoreService service = BlobstoreServiceFactory.getBlobstoreService();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// doGet simplesmente chama o doPost
		this.doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		com.uaijug.dengue.entidade.Foco foco = null;
		ObjectOutputStream ous = new ObjectOutputStream(response.getOutputStream());
		ObjectInputStream ois = new ObjectInputStream(request.getInputStream());

		try {
			foco = (com.uaijug.dengue.entidade.Foco) ois.readObject();
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}			
		if (foco != null && foco.getId() != null && !foco.getId().equals(0)) {
			ous.writeObject(getFoco(foco.getId()));
		} else {
			ous.writeObject(getFocos());
		}
		ous.flush();
		ous.close();
	}

	// cria uma lista de Focos recuperados do datastore
	private List<com.uaijug.dengue.entidade.Foco> getFocos() throws IOException {
		List<com.uaijug.dengue.entidade.Foco> focos = new ArrayList<com.uaijug.dengue.entidade.Foco>();
		String query = "select from " + Foco.class.getName();
		@SuppressWarnings("unchecked")
		List<Foco> focosServer = (List<Foco>) pm.newQuery(query).execute();
		for (Foco foco : focosServer) {
			focos.add(foco.convertToDTO());
		}
		return focos;
	}

	private com.uaijug.dengue.entidade.Foco getFoco(Long id) {
		Key keyId = KeyFactory.createKey(Foco.class.getSimpleName(), id);
		Foco foco = pm.getObjectById(Foco.class, keyId);
		return foco.convertToDTO();
	}
}
